package com.charging.business.constants;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.charging.business.config.MinFeeManager;
import com.charging.business.exception.CustomizeException;
import com.charging.common.utils.DateUtils;
import com.charging.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author JerryLu
 * @date 2024/12/3 10:23
 * @description 山西兜底费率版本下载及加载线程
 */
@Component
@Slf4j
public class JinGbMinFeeThread {
    private final Logger logger = LoggerFactory.getLogger(JinGbMinFeeThread.class);

    private final AtomicInteger counter = new AtomicInteger(0);

    private final MinFeeManager minFeeManager;

    private final RestTemplate restTemplate;

    @Value("${app.stationId}")
    private String stationId;

    @Value("${app.nameServerIp}")
    private String nameServerIp;

    @Autowired
    public JinGbMinFeeThread(MinFeeManager minFeeManager, RestTemplate restTemplate) {
        this.minFeeManager = minFeeManager;
        this.restTemplate = restTemplate;
    }

    //    @Async("asyncServiceExecutor")
    public void execute() throws CustomizeException {
//        try {
        String loadGMinFeeMsg = loadMinFee(false);
//            Thread.sleep(0);
        if (StringUtils.isNotEmpty(loadGMinFeeMsg)) {
            throw new CustomizeException(loadGMinFeeMsg);
        }
//        } catch (InterruptedException e) {
//             恢复中断状态
//            Thread.currentThread().interrupt();
//            logger.warn("初始化获取费额费率版本号线程加载异常: " + e.getMessage());
//        }
    }

    /**
     * 每周二周五每隔半小时更新最小费额费率版本号
     */
    @Scheduled(cron = "1 30 * ? * 3,6")
    public void run() {
        try {
            loadMinFee(true);
        } catch (Exception e) {
            logger.error("更新兜底费率出错：[{}][{}]", e.getMessage(), e.getMessage().replace("\r", " ").replace("\n", " "));
        }
    }

    private String loadMinFee(boolean state) throws CustomizeException {
        String errMsg = "";
        String fileName = String.format("BASIC_LIST_VERSIONQUERY_REQ_%s_%s.json", stationId, DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSSSSS));

        JSONObject json = new JSONObject();
        json.put("filename", fileName);
        json.put("encryptType", "");
        json.put("timestamp", "");
        json.put("version", "2.0");
        json.put("sign", "");
        json.put("signType", "None");
        JSONObject json1 = new JSONObject();
        json1.put("msgId", stationId + DateUtils.dateTimeNow(DateUtils.YYYYMMDDHH) + getNextRequestId());
        json.put("bizContent", json1);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json; charset=utf-8");
        headers.set("Accept-Charset", "utf-8");
        HttpEntity<String> entity = new HttpEntity<>(json.toString(), headers);

        try {
            long start = System.currentTimeMillis();
            ResponseEntity<String> response = restTemplate.postForEntity(nameServerIp, entity, String.class);
            JSONObject jsonResult = JSON.parseObject(response.getBody());
            if (jsonResult.getInteger("statusCode") == 0) {
                JSONObject biz = JSON.parseObject(jsonResult.getString("bizContent"));
                if (biz.getInteger("code") == 0) {
                    String spcRateVersion = biz.getString("spcRateVersion");
                    if (spcRateVersion != null) {
                        this.minFeeManager.setMinFeeVersion(spcRateVersion);
                        long end = System.currentTimeMillis();
                        logger.info("{}费率版本号成功{},耗时{}毫秒", state ? "更新" : "获取", spcRateVersion, (end - start));
                    }
                } else {
                    errMsg = jsonResult.getString("codeInfo");
                    logger.error("{}费率版本号获取失败：{}", state ? "更新" : "获取", jsonResult.getString("codeInfo"));
                }
            } else {
                logger.error("{}费率版本号获取失败：{}", state ? "更新" : "获取", jsonResult.getString("codeInfo"));
                errMsg = jsonResult.getString("codeInfo");
            }
        } catch (ResourceAccessException e) {
            throw new CustomizeException("获取费率版本超时");
        } catch (Exception e) {
            logger.error("率版本号获取异常：{}", e.getMessage());
            errMsg = e.getMessage();
        }
        return errMsg;
    }

    /**
     * 计数器自增
     *
     * @return
     */
    public synchronized String getNextRequestId() {
        int nextValue = counter.incrementAndGet();
        return String.format("%06d", nextValue);
    }
}
